home *** CD-ROM | disk | FTP | other *** search
/ Openstep 4.2 (Developer) / Openstep Developer 4.2.iso / NextDeveloper / Source / GNU / make / make-3.74 / function.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-02-25  |  32.5 KB  |  1,315 lines

  1. /* Variable function expansion for GNU Make.
  2. Copyright (C) 1988, 89, 91, 92, 93, 94, 95 Free Software Foundation, Inc.
  3. This file is part of GNU Make.
  4.  
  5. GNU Make is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9.  
  10. GNU Make is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. GNU General Public License for more details.
  14.  
  15. You should have received a copy of the GNU General Public License
  16. along with GNU Make; see the file COPYING.  If not, write to
  17. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  18.  
  19. #include "make.h"
  20. #include "variable.h"
  21. #include "dep.h"
  22. #include "commands.h"
  23. #include "job.h"
  24.  
  25. #if defined (__MSDOS__) || defined (WIN32)
  26. #include <process.h>
  27. #include <fcntl.h>
  28. #endif
  29.  
  30. static char *string_glob ();
  31.  
  32. /* Store into VARIABLE_BUFFER at O the result of scanning TEXT and replacing
  33.    each occurrence of SUBST with REPLACE. TEXT is null-terminated.  SLEN is
  34.    the length of SUBST and RLEN is the length of REPLACE.  If BY_WORD is
  35.    nonzero, substitutions are done only on matches which are complete
  36.    whitespace-delimited words.  If SUFFIX_ONLY is nonzero, substitutions are
  37.    done only at the ends of whitespace-delimited words.  */
  38.    
  39. char *
  40. subst_expand (o, text, subst, replace, slen, rlen, by_word, suffix_only)
  41.      char *o;
  42.      char *text;
  43.      char *subst, *replace;
  44.      unsigned int slen, rlen;
  45.      int by_word, suffix_only;
  46. {
  47.   register char *t = text;
  48.   register char *p;
  49.  
  50.   if (slen == 0 && !by_word && !suffix_only)
  51.     {
  52.       /* The first occurrence of "" in any string is its end.  */
  53.       o = variable_buffer_output (o, t, strlen (t));
  54.       if (rlen > 0)
  55.     o = variable_buffer_output (o, replace, rlen);
  56.       return o;
  57.     }
  58.  
  59.   do
  60.     {
  61.       if ((by_word | suffix_only) && slen == 0)
  62.     /* When matching by words, the empty string should match
  63.        the end of each word, rather than the end of the whole text.  */
  64.     p = end_of_token (next_token (t));
  65.       else
  66.     {
  67.       p = sindex (t, 0, subst, slen);
  68.       if (p == 0)
  69.         {
  70.           /* No more matches.  Output everything left on the end.  */
  71.           o = variable_buffer_output (o, t, strlen (t));
  72.           return o;
  73.         }
  74.     }
  75.  
  76.       /* Output everything before this occurrence of the string to replace.  */
  77.       if (p > t)
  78.     o = variable_buffer_output (o, t, p - t);
  79.  
  80.       /* If we're substituting only by fully matched words,
  81.      or only at the ends of words, check that this case qualifies.  */
  82.       if ((by_word
  83.        && ((p > t && !isblank (p[-1]))
  84.            || (p[slen] != '\0' && !isblank (p[slen]))))
  85.       || (suffix_only
  86.           && (p[slen] != '\0' && !isblank (p[slen]))))
  87.     /* Struck out.  Output the rest of the string that is
  88.        no longer to be replaced.  */
  89.     o = variable_buffer_output (o, subst, slen);
  90.       else if (rlen > 0)
  91.     /* Output the replacement string.  */
  92.     o = variable_buffer_output (o, replace, rlen);
  93.  
  94.       /* Advance T past the string to be replaced.  */
  95.       t = p + slen;
  96.     } while (*t != '\0');
  97.  
  98.   return o;
  99. }
  100.  
  101.  
  102. /* Store into VARIABLE_BUFFER at O the result of scanning TEXT
  103.    and replacing strings matching PATTERN with REPLACE.
  104.    If PATTERN_PERCENT is not nil, PATTERN has already been
  105.    run through find_percent, and PATTERN_PERCENT is the result.
  106.    If REPLACE_PERCENT is not nil, REPLACE has already been
  107.    run through find_percent, and REPLACE_PERCENT is the result.  */
  108.  
  109. char *
  110. patsubst_expand (o, text, pattern, replace, pattern_percent, replace_percent)
  111.      char *o;
  112.      char *text;
  113.      register char *pattern, *replace;
  114.      register char *pattern_percent, *replace_percent;
  115. {
  116.   register int pattern_prepercent_len, pattern_postpercent_len;
  117.   register int replace_prepercent_len, replace_postpercent_len;
  118.   register char *t;
  119.   unsigned int len;
  120.   int doneany = 0;
  121.  
  122.   /* We call find_percent on REPLACE before checking PATTERN so that REPLACE
  123.      will be collapsed before we call subst_expand if PATTERN has no %.  */
  124.   if (replace_percent == 0)
  125.     replace_percent = find_percent (replace);
  126.   if (replace_percent != 0)
  127.     {
  128.       /* Record the length of REPLACE before and after the % so
  129.      we don't have to compute these lengths more than once.  */
  130.       replace_prepercent_len = replace_percent - replace;
  131.       replace_postpercent_len = strlen (replace_percent + 1);
  132.     }
  133.   else
  134.     /* We store the length of the replacement
  135.        so we only need to compute it once.  */
  136.     replace_prepercent_len = strlen (replace);
  137.  
  138.   if (pattern_percent == 0)
  139.     pattern_percent = find_percent (pattern);
  140.   if (pattern_percent == 0)
  141.     /* With no % in the pattern, this is just a simple substitution.  */
  142.     return subst_expand (o, text, pattern, replace,
  143.              strlen (pattern), strlen (replace), 1, 0);
  144.  
  145.   /* Record the length of PATTERN before and after the %
  146.      so we don't have to compute it more than once.  */
  147.   pattern_prepercent_len = pattern_percent - pattern;
  148.   pattern_postpercent_len = strlen (pattern_percent + 1);
  149.  
  150.   while ((t = find_next_token (&text, &len)) != 0)
  151.     {
  152.       int fail = 0;
  153.  
  154.       /* Is it big enough to match?  */
  155.       if (len < pattern_prepercent_len + pattern_postpercent_len)
  156.     fail = 1;
  157.  
  158.       /* Does the prefix match?  */
  159.       if (!fail && pattern_prepercent_len > 0
  160.       && (*t != *pattern
  161.           || t[pattern_prepercent_len - 1] != pattern_percent[-1]
  162.           || strncmp (t + 1, pattern + 1, pattern_prepercent_len - 1)))
  163.     fail = 1;
  164.  
  165.       /* Does the suffix match?  */
  166.       if (!fail && pattern_postpercent_len > 0
  167.       && (t[len - 1] != pattern_percent[pattern_postpercent_len]
  168.           || t[len - pattern_postpercent_len] != pattern_percent[1]
  169.           || strncmp (&t[len - pattern_postpercent_len],
  170.               &pattern_percent[1], pattern_postpercent_len - 1)))
  171.     fail = 1;
  172.  
  173.       if (fail)
  174.     /* It didn't match.  Output the string.  */
  175.     o = variable_buffer_output (o, t, len);
  176.       else
  177.     {
  178.       /* It matched.  Output the replacement.  */
  179.  
  180.       /* Output the part of the replacement before the %.  */
  181.       o = variable_buffer_output (o, replace, replace_prepercent_len);
  182.  
  183.       if (replace_percent != 0)
  184.         {
  185.           /* Output the part of the matched string that
  186.          matched the % in the pattern.  */
  187.           o = variable_buffer_output (o, t + pattern_prepercent_len,
  188.                       len - (pattern_prepercent_len
  189.                          + pattern_postpercent_len));
  190.           /* Output the part of the replacement after the %.  */
  191.           o = variable_buffer_output (o, replace_percent + 1,
  192.                       replace_postpercent_len);
  193.         }
  194.     }
  195.  
  196.       /* Output a space, but not if the replacement is "".  */
  197.       if (fail || replace_prepercent_len > 0
  198.       || (replace_percent != 0 && len + replace_postpercent_len > 0))
  199.     {
  200.       o = variable_buffer_output (o, " ", 1);
  201.       doneany = 1;
  202.     }
  203.     }
  204.   if (doneany)
  205.     /* Kill the last space.  */
  206.     --o;
  207.  
  208.   return o;
  209. }
  210.  
  211. /* Handle variable-expansion-time functions such as $(dir foo/bar) ==> foo/  */
  212.  
  213. /* These enumeration constants distinguish the
  214.    various expansion-time built-in functions.  */
  215.  
  216. enum function
  217.   {
  218.     function_subst,
  219.     function_addsuffix,
  220.     function_addprefix,
  221.     function_dir,
  222.     function_notdir,
  223.     function_suffix,
  224.     function_basename,
  225.     function_wildcard,
  226.     function_firstword,
  227.     function_word,
  228.     function_words,
  229.     function_findstring,
  230.     function_strip,
  231.     function_join,
  232.     function_patsubst,
  233.     function_filter,
  234.     function_filter_out,
  235.     function_foreach,
  236.     function_sort,
  237.     function_origin,
  238.     function_shell,
  239.     function_invalid
  240.   };
  241.  
  242. /* Greater than the length of any function name.  */
  243. #define MAXFUNCTIONLEN 11
  244.  
  245. /* The function names and lengths of names, for looking them up.  */
  246.  
  247. static struct
  248.   {
  249.     char *name;
  250.     unsigned int len;
  251.     enum function function;
  252.   } function_table[] =
  253.   {
  254.     { "subst", 5, function_subst },
  255.     { "addsuffix", 9, function_addsuffix },
  256.     { "addprefix", 9, function_addprefix },
  257.     { "dir", 3, function_dir },
  258.     { "notdir", 6, function_notdir },
  259.     { "suffix", 6, function_suffix },
  260.     { "basename", 8, function_basename },
  261.     { "wildcard", 8, function_wildcard },
  262.     { "firstword", 9, function_firstword },
  263.     { "word", 4, function_word },
  264.     { "words", 5, function_words },
  265.     { "findstring", 10, function_findstring },
  266.     { "strip", 5, function_strip },
  267.     { "join", 4, function_join },
  268.     { "patsubst", 8, function_patsubst },
  269.     { "filter", 6, function_filter },
  270.     { "filter-out", 10, function_filter_out },
  271.     { "foreach", 7, function_foreach },
  272.     { "sort", 4, function_sort },
  273.     { "origin", 6, function_origin },
  274.     { "shell", 5, function_shell },
  275.     { 0, 0, function_invalid }
  276.   };
  277.  
  278. /* Return 1 if PATTERN matches WORD, 0 if not.  */
  279.  
  280. int
  281. pattern_matches (pattern, percent, word)
  282.      register char *pattern, *percent, *word;
  283. {
  284.   unsigned int sfxlen, wordlen;
  285.  
  286.   if (percent == 0)
  287.     {
  288.       unsigned int len = strlen (pattern) + 1;
  289.       char *new = (char *) alloca (len);
  290.       bcopy (pattern, new, len);
  291.       pattern = new;
  292.       percent = find_percent (pattern);
  293.       if (percent == 0)
  294.     return streq (pattern, word);
  295.     }
  296.  
  297.   sfxlen = strlen (percent + 1);
  298.   wordlen = strlen (word);
  299.  
  300.   if (wordlen < (percent - pattern) + sfxlen
  301.       || strncmp (pattern, word, percent - pattern))
  302.     return 0;
  303.  
  304.   return !strcmp (percent + 1, word + (wordlen - sfxlen));
  305. }
  306.  
  307. int shell_function_pid = 0, shell_function_completed;
  308.  
  309. /* Perform the function specified by FUNCTION on the text at TEXT.
  310.    END is points to the end of the argument text (exclusive).
  311.    The output is written into VARIABLE_BUFFER starting at O.  */
  312.  
  313. /* Note this absorbs a semicolon and is safe to use in conditionals.  */
  314. #define BADARGS(func)                                  \
  315.   if (reading_filename != 0)                              \
  316.     makefile_fatal (reading_filename, *reading_lineno_ptr,              \
  317.             "insufficient arguments to function `%s'",               \
  318.             func);                              \
  319.   else                                          \
  320.     fatal ("insufficient arguments to function `%s'", func)
  321.  
  322. static char *
  323. expand_function (o, function, text, end)
  324.      char *o;
  325.      enum function function;
  326.      char *text;
  327.      char *end;
  328. {
  329.   char *p, *p2, *p3;
  330.   unsigned int i, len;
  331.   int doneany = 0;
  332.   int count;
  333.   char endparen = *end, startparen = *end == ')' ? '(' : '{';
  334.  
  335.   switch (function)
  336.     {
  337.     default:
  338.       abort ();
  339.       break;
  340.       
  341.     case function_shell:
  342.       {
  343.     char **argv, **envp;
  344.     char *error_prefix;
  345.     int pipedes[2];
  346.     int pid;
  347.  
  348.     /* Expand the command line.  */
  349.     text = expand_argument (text, end);
  350.  
  351.     /* Construct the argument list.  */
  352.     argv = construct_command_argv (text, (char *) NULL, (struct file *) 0);
  353.     if (argv == 0)
  354.       break;
  355.  
  356.     /* Using a target environment for `shell' loses in cases like:
  357.            export var = $(shell echo foobie) 
  358.        because target_environment hits a loop trying to expand $(var)
  359.        to put it in the environment.  This is even more confusing when
  360.        var was not explicitly exported, but just appeared in the
  361.        calling environment.  */
  362. #if 1
  363.     envp = environ;
  364. #else
  365.     /* Construct the environment.  */
  366.     envp = target_environment ((struct file *) 0);
  367. #endif
  368.  
  369.     /* For error messages.  */
  370.     if (reading_filename != 0)
  371.       {
  372.         error_prefix = (char *) alloca (strlen (reading_filename) + 100);
  373.         sprintf (error_prefix,
  374.              "%s:%u: ", reading_filename, *reading_lineno_ptr);
  375.       }
  376.     else
  377.       error_prefix = "";
  378.  
  379. #if ! (defined (__MSDOS__) || defined (WIN32))
  380.     if (pipe (pipedes) < 0)
  381.       {
  382.         perror_with_name (error_prefix, "pipe");
  383.         break;
  384.       }
  385.  
  386.     pid = vfork ();
  387.     if (pid < 0)
  388.       perror_with_name (error_prefix, "fork");
  389.     else if (pid == 0)
  390.       child_execute_job (0, pipedes[1], argv, envp);
  391.     else
  392.       {
  393.         /* We are the parent.  */
  394.  
  395.         char *buffer;
  396.         unsigned int maxlen;
  397.         int cc;
  398.  
  399.         /* Free the storage only the child needed.  */
  400.         free (argv[0]);
  401.         free ((char *) argv);
  402. #if 0
  403.         for (i = 0; envp[i] != 0; ++i)
  404.           free (envp[i]);
  405.         free ((char *) envp);
  406. #endif
  407.  
  408.         /* Record the PID for reap_children.  */
  409.         shell_function_pid = pid;
  410.         shell_function_completed = 0;
  411.  
  412.  
  413.         /* Set up and read from the pipe.  */
  414.  
  415.         maxlen = 200;
  416.         buffer = (char *) xmalloc (maxlen + 1);
  417.  
  418.         /* Close the write side of the pipe.  */
  419.         (void) close (pipedes[1]);
  420.  
  421.         /* Read from the pipe until it gets EOF.  */
  422.         i = 0;
  423.         do
  424.           {
  425.         if (i == maxlen)
  426.           {
  427.             maxlen += 512;
  428.             buffer = (char *) xrealloc (buffer, maxlen + 1);
  429.           }
  430.  
  431.         errno = 0;
  432.         cc = read (pipedes[0], &buffer[i], maxlen - i);
  433.         if (cc > 0)
  434.           i += cc;
  435.           }
  436. #ifdef EINTR
  437.         while (cc > 0 || errno == EINTR);
  438. #else
  439.         while (cc > 0);
  440. #endif
  441.  
  442.         /* Close the read side of the pipe.  */
  443.         (void) close (pipedes[0]);
  444.  
  445.         /* Loop until child_handler sets shell_function_completed
  446.            to the status of our child shell.  */
  447.         while (shell_function_completed == 0)
  448.           reap_children (1, 0);
  449.  
  450.         shell_function_pid = 0;
  451.  
  452.         /* The child_handler function will set shell_function_completed
  453.            to 1 when the child dies normally, or to -1 if it
  454.            dies with status 127, which is most likely an exec fail.  */
  455.  
  456.         if (shell_function_completed == -1)
  457.           {
  458.         /* This most likely means that the execvp failed,
  459.            so we should just write out the error message
  460.            that came in over the pipe from the child.  */
  461.         fputs (buffer, stderr);
  462.         fflush (stderr);
  463.           }
  464.         else
  465.           {
  466.         /* The child finished normally.  Replace all
  467.            newlines in its output with spaces, and put
  468.            that in the variable output buffer.  */
  469.         if (i > 0)
  470.           {
  471.             if (buffer[i - 1] == '\n')
  472.               buffer[--i] = '\0';
  473.             else
  474.               buffer[i] = '\0';
  475.             p = buffer;
  476.             while ((p = index (p, '\n')) != 0)
  477.               *p++ = ' ';
  478.             o = variable_buffer_output (o, buffer, i);
  479.           }
  480.           }
  481.  
  482.         free (buffer);
  483.       }
  484. #else    /* MSDOS.  */
  485.          {
  486.        /* MS-DOS can't do fork, but it can do spawn.  However, this
  487.           means that we don't have an opportunity to reopen stdout to
  488.           trap it.  Thus, we save our own stdout onto a new descriptor
  489.           and dup a temp file's descriptor onto our stdout temporarily.
  490.           After we spawn the shell program, we dup our own stdout back
  491.           to the stdout descriptor.  The buffer reading is the same as
  492.           above, except that we're now reading from a file.  */
  493.  
  494.        int save_stdout;
  495.        int child_stdout;
  496.        char tmp_output[FILENAME_MAX];
  497.            const char *tempdir;
  498.        FILE *child_stream;
  499.        unsigned int maxlen = 200;
  500.        int cc;
  501.        char *buffer;
  502.  
  503.            tempdir = getenv("TEMP");
  504.            if (!tempdir) fatal("Please set the TEMP environment variable"); /* Better than a bus error in strcpy */
  505.            strcpy (tmp_output, tempdir);
  506.            strcat (tmp_output, "\\shXXXXXX");
  507.        mktemp (tmp_output);
  508.        child_stdout = open (tmp_output,
  509.                 O_WRONLY|O_CREAT|O_TRUNC|O_TEXT, 0644);
  510.            save_stdout = dup (1);
  511.        dup2 (child_stdout, 1);
  512.        clean_spawnvp (P_WAIT, argv[0], argv);
  513.        dup2 (save_stdout, 1);
  514.        close (child_stdout);
  515.        close (save_stdout);
  516.  
  517.        child_stdout = open (tmp_output, O_RDONLY|O_TEXT, 0644);
  518.  
  519.        buffer = xmalloc (maxlen);
  520.        i = 0;
  521.        do
  522.          {
  523.            if (i == maxlen)
  524.          {
  525.            maxlen += 512;
  526.            buffer = (char *) xrealloc (buffer, maxlen + 1);
  527.          }
  528.  
  529.            cc = read (child_stdout, &buffer[i], maxlen - i);
  530.            if (cc > 0)
  531.          i += cc;
  532.          } while (cc > 0);
  533.  
  534.        close (child_stdout);
  535.        unlink (tmp_output);
  536.  
  537.        if (i > 0)
  538.          {
  539.            if (buffer[i - 1] == '\n')
  540.          buffer[--i] = '\0';
  541.            else
  542.          buffer[i] = '\0';
  543.            p = buffer;
  544.            while ((p = index (p, '\n')) != 0)
  545.          *p++ = ' ';
  546.            o = variable_buffer_output (o, buffer, i);
  547.          }
  548.        free (buffer);
  549.      }
  550. #endif    /* Not MSDOS.  */
  551.  
  552.     free (text);
  553.     break;
  554.       }
  555.  
  556.     case function_origin:
  557.       /* Expand the argument.  */
  558.       text = expand_argument (text, end);
  559.  
  560.       {
  561.     register struct variable *v = lookup_variable (text, strlen (text));
  562.     if (v == 0)
  563.       o = variable_buffer_output (o, "undefined", 9);
  564.     else
  565.       switch (v->origin)
  566.         {
  567.         default:
  568.         case o_invalid:
  569.           abort ();
  570.           break;
  571.         case o_default:
  572.           o = variable_buffer_output (o, "default", 7);
  573.           break;
  574.         case o_env:
  575.           o = variable_buffer_output (o, "environment", 11);
  576.           break;
  577.         case o_file:
  578.           o = variable_buffer_output (o, "file", 4);
  579.           break;
  580.         case o_env_override:
  581.           o = variable_buffer_output (o, "environment override", 20);
  582.           break;
  583.         case o_command:
  584.           o = variable_buffer_output (o, "command line", 12);
  585.           break;
  586.         case o_override:
  587.           o = variable_buffer_output (o, "override", 8);
  588.           break;
  589.         case o_automatic:
  590.           o = variable_buffer_output (o, "automatic", 9);
  591.           break;
  592.         }
  593.       }
  594.  
  595.       free (text);
  596.       break;
  597.       
  598.     case function_sort:
  599.       /* Expand the argument.  */
  600.       text = expand_argument (text, end);
  601.  
  602.       {
  603.     char **words = (char **) xmalloc (10 * sizeof (char *));
  604.     unsigned int nwords = 10;
  605.     register unsigned int wordi = 0;
  606.     char *t;
  607.  
  608.     /* Chop TEXT into words and put them in WORDS.  */
  609.     t = text;
  610.     while ((p = find_next_token (&t, &len)) != 0)
  611.       {
  612.         if (wordi >= nwords - 1)
  613.           {
  614.         nwords *= 2;
  615.         words = (char **) xrealloc ((char *) words,
  616.                         nwords * sizeof (char *));
  617.           }    
  618.         words[wordi++] = savestring (p, len);
  619.       }
  620.  
  621.     if (wordi > 0)
  622.       {
  623.         /* Now sort the list of words.  */
  624.         qsort ((char *) words, wordi, sizeof (char *), alpha_compare);
  625.  
  626.         /* Now write the sorted list.  */
  627.         for (i = 0; i < wordi; ++i)
  628.           {
  629.         len = strlen (words[i]);
  630.         if (i == wordi - 1 || strlen (words[i + 1]) != len
  631.             || strcmp (words[i], words[i + 1]))
  632.           {
  633.             o = variable_buffer_output (o, words[i], len);
  634.             o = variable_buffer_output (o, " ", 1);
  635.           }
  636.         free (words[i]);
  637.           }
  638.         /* Kill the last space.  */
  639.         --o;
  640.       }
  641.  
  642.     free ((char *) words);
  643.       }
  644.  
  645.       free (text);
  646.       break;
  647.       
  648.     case function_foreach:
  649.       {
  650.     /* Get three comma-separated arguments but
  651.        expand only the first two.  */
  652.     char *var, *list;
  653.     register struct variable *v;
  654.  
  655.     count = 0;
  656.     for (p = text; p < end; ++p)
  657.       {
  658.         if (*p == startparen)
  659.           ++count;
  660.         else if (*p == endparen)
  661.           --count;
  662.         else if (*p == ',' && count <= 0)
  663.           break;
  664.       }
  665.     if (p == end)
  666.       BADARGS ("foreach");
  667.     var = expand_argument (text, p);
  668.  
  669.     p2 = p + 1;
  670.     count = 0;
  671.     for (p = p2; p < end; ++p)
  672.       {
  673.         if (*p == startparen)
  674.           ++count;
  675.         else if (*p == endparen)
  676.           --count;
  677.         else if (*p == ',' && count <= 0)
  678.           break;
  679.       }
  680.     if (p == end)
  681.       BADARGS ("foreach");
  682.     list = expand_argument (p2, p);
  683.  
  684.     ++p;
  685.     text = savestring (p, end - p);
  686.  
  687.     push_new_variable_scope ();
  688.     v = define_variable (var, strlen (var), "", o_automatic, 0);
  689.     p3 = list;
  690.     while ((p = find_next_token (&p3, &len)) != 0)
  691.       {
  692.         char *result;
  693.         char save = p[len];
  694.         p[len] = '\0';
  695.         v->value = p;
  696.         result = allocated_variable_expand (text);
  697.         p[len] = save;
  698.  
  699.         o = variable_buffer_output (o, result, strlen (result));
  700.         o = variable_buffer_output (o, " ", 1);
  701.         doneany = 1;
  702.         free (result);
  703.       }
  704.     if (doneany)
  705.       /* Kill the last space.  */
  706.       --o;
  707.  
  708.     pop_variable_scope ();
  709.  
  710.     free (var);
  711.     free (list);
  712.     free (text);
  713.       }
  714.       break;
  715.  
  716.     case function_filter:
  717.     case function_filter_out:
  718.       {
  719.     struct word
  720.       {
  721.         struct word *next;
  722.         char *word;
  723.         int matched;
  724.       } *words, *wordtail, *wp;
  725.  
  726.     /* Get two comma-separated arguments and expand each one.  */
  727.     count = 0;
  728.     for (p = text; p < end; ++p)
  729.       {
  730.         if (*p == startparen)
  731.           ++count;
  732.         else if (*p == endparen)
  733.           --count;
  734.         else if (*p == ',' && count <= 0)
  735.           break;
  736.       }
  737.     if (p == end)
  738.       BADARGS (function == function_filter ? "filter" : "filter-out");
  739.     p2 = expand_argument (text, p);
  740.     
  741.     text = expand_argument (p + 1, end);
  742.  
  743.     /* Chop TEXT up into words and then run each pattern through.  */
  744.     words = wordtail = 0;
  745.     p3 = text;
  746.     while ((p = find_next_token (&p3, &len)) != 0)
  747.       {
  748.         struct word *w = (struct word *) alloca (sizeof (struct word));
  749.         if (words == 0)
  750.           words = w;
  751.         else
  752.           wordtail->next = w;
  753.         wordtail = w;
  754.  
  755.         if (*p3 != '\0')
  756.           ++p3;
  757.         p[len] = '\0';
  758.         w->word = p;
  759.         w->matched = 0;
  760.       }
  761.  
  762.     if (words != 0)
  763.       {
  764.         wordtail->next = 0;
  765.  
  766.         /* Run each pattern through the words, killing words.  */
  767.         p3 = p2;
  768.         while ((p = find_next_token (&p3, &len)) != 0)
  769.           {
  770.         char *percent;
  771.         char save = p[len];
  772.         p[len] = '\0';
  773.  
  774.         percent = find_percent (p);
  775.         for (wp = words; wp != 0; wp = wp->next)
  776.           wp->matched |= (percent == 0 ? streq (p, wp->word)
  777.                   : pattern_matches (p, percent, wp->word));
  778.  
  779.         p[len] = save;
  780.           }
  781.  
  782.         /* Output the words that matched (or didn't, for filter-out).  */
  783.         for (wp = words; wp != 0; wp = wp->next)
  784.           if (function == function_filter ? wp->matched : !wp->matched)
  785.         {
  786.           o = variable_buffer_output (o, wp->word, strlen (wp->word));
  787.           o = variable_buffer_output (o, " ", 1);
  788.           doneany = 1;
  789.         }
  790.         if (doneany)
  791.           /* Kill the last space.  */
  792.           --o;
  793.       }
  794.  
  795.     free (p2);
  796.     free (text);
  797.       }
  798.       break;
  799.       
  800.     case function_patsubst:
  801.       /* Get three comma-separated arguments and expand each one.  */
  802.       count = 0;
  803.       for (p = text; p < end; ++p)
  804.     {
  805.       if (*p == startparen)
  806.         ++count;
  807.       else if (*p == endparen)
  808.         --count;
  809.       else if (*p == ',' && count <= 0)
  810.         break;
  811.     }
  812.       if (p == end)
  813.     BADARGS ("patsubst");
  814.  
  815.       p2 = p;
  816.       count = 0;
  817.       for (++p; p < end; ++p)
  818.     {
  819.       if (*p == startparen)
  820.         ++count;
  821.       else if (*p == endparen)
  822.         --count;
  823.       else if (*p == ',' && count <= 0)
  824.         break;
  825.     }
  826.       if (p == end)
  827.     BADARGS ("patsubst");
  828.  
  829.       text = expand_argument (text, p2);
  830.       p3 = expand_argument (p2 + 1, p);
  831.       p2 = expand_argument (p + 1, end);
  832.       
  833.       o = patsubst_expand (o, p2, text, p3, (char *) 0, (char *) 0);
  834.       
  835.       free (text);
  836.       free (p3);
  837.       free (p2);
  838.       break;
  839.  
  840.     case function_join:
  841.       /* Get two comma-separated arguments and expand each one.  */
  842.       count = 0;
  843.       for (p = text; p < end; ++p)
  844.     {
  845.       if (*p == startparen)
  846.         ++count;
  847.       else if (*p == endparen)
  848.         --count;
  849.       else if (*p == ',' && count <= 0)
  850.         break;
  851.     }
  852.       if (p == end)
  853.     BADARGS ("join");
  854.       text = expand_argument (text, p);
  855.  
  856.       p = expand_argument (p + 1, end);
  857.       
  858.       {
  859.     /* Write each word of the first argument directly followed
  860.        by the corresponding word of the second argument.
  861.        If the two arguments have a different number of words,
  862.        the excess words are just output separated by blanks.  */
  863.     register char *tp, *pp;
  864.     p2 = text;
  865.     p3 = p;
  866.     do
  867.       {
  868.         unsigned int tlen, plen;
  869.  
  870.         tp = find_next_token (&p2, &tlen);
  871.         if (tp != 0)
  872.           o = variable_buffer_output (o, tp, tlen);
  873.         
  874.         pp = find_next_token (&p3, &plen);
  875.         if (pp != 0)
  876.           o = variable_buffer_output (o, pp, plen);
  877.         
  878.         if (tp != 0 || pp != 0)
  879.           {
  880.         o = variable_buffer_output (o, " ", 1);
  881.         doneany = 1;
  882.           }
  883.       }
  884.     while (tp != 0 || pp != 0);
  885.     if (doneany)
  886.       /* Kill the last blank.  */
  887.       --o;
  888.       }
  889.       
  890.       free (text);
  891.       free (p);
  892.       break;
  893.       
  894.     case function_strip:
  895.       /* Expand the argument.  */
  896.       text = expand_argument (text, end);
  897.  
  898.       p2 = text;
  899.       while ((p = find_next_token (&p2, &i)) != 0)
  900.     {
  901.       o = variable_buffer_output (o, p, i);
  902.       o = variable_buffer_output (o, " ", 1);
  903.       doneany = 1;
  904.     }
  905.       if (doneany)
  906.     /* Kill the last space.  */
  907.     --o;
  908.       
  909.       free (text);
  910.       break;
  911.       
  912.     case function_wildcard:
  913.       text = expand_argument (text, end);
  914.       
  915.       p = string_glob (text);
  916.       o = variable_buffer_output (o, p, strlen (p));
  917.       
  918.       free (text);
  919.       break;
  920.       
  921.     case function_subst:
  922.       /* Get three comma-separated arguments and expand each one.  */
  923.       count = 0;
  924.       for (p = text; p < end; ++p)
  925.     {
  926.       if (*p == startparen)
  927.         ++count;
  928.       else if (*p == endparen)
  929.         --count;
  930.       else if (*p == ',' && count <= 0)
  931.         break;
  932.     }
  933.       if (p == end)
  934.     BADARGS ("subst");
  935.  
  936.       p2 = p;
  937.       count = 0;
  938.       for (++p; p < end; ++p)
  939.     {
  940.       if (*p == startparen)
  941.         ++count;
  942.       else if (*p == endparen)
  943.         --count;
  944.       else if (*p == ',' && count <= 0)
  945.         break;
  946.     }
  947.       if (p == end)
  948.     BADARGS ("subst");
  949.  
  950.       text = expand_argument (text, p2);
  951.       p3 = expand_argument (p2 + 1, p);
  952.       p2 = expand_argument (p + 1, end);
  953.       
  954.       o = subst_expand (o, p2, text, p3, strlen (text), strlen (p3), 0, 0);
  955.       
  956.       free (text);
  957.       free (p3);
  958.       free (p2);
  959.       break;
  960.       
  961.     case function_firstword:
  962.       /* Expand the argument.  */
  963.       text = expand_argument (text, end);
  964.  
  965.       /* Find the first word in TEXT.  */
  966.       p2 = text;
  967.       p = find_next_token (&p2, &i);
  968.       if (p != 0)
  969.     o = variable_buffer_output (o, p, i);
  970.       
  971.       free (text);
  972.       break;
  973.       
  974.     case function_word:
  975.       /* Get two comma-separated arguments and expand each one.  */
  976.       count = 0;
  977.       for (p = text; p < end; ++p)
  978.     {
  979.       if (*p == startparen)
  980.         ++count;
  981.       else if (*p == endparen)
  982.         --count;
  983.       else if (*p == ',' && count <= 0)
  984.         break;
  985.     }
  986.       if (p == end)
  987.     BADARGS ("word");
  988.       text = expand_argument (text, p);
  989.  
  990.       p3 = expand_argument (p + 1, end);
  991.  
  992.       /* Check the first argument.  */
  993.       for (p2 = text; *p2 != '\0'; ++p2)
  994.     if (*p2 < '0' || *p2 > '9')
  995.       {
  996.         if (reading_filename != 0)
  997.           makefile_fatal (reading_filename, *reading_lineno_ptr,
  998.                   "non-numeric first argument to `word' function");
  999.         else
  1000.           fatal ("non-numeric first argument to `word' function");
  1001.       }
  1002.  
  1003.       i = (unsigned int) atoi (text);
  1004.       if (i == 0)
  1005.     {
  1006.       if (reading_filename != 0)
  1007.         makefile_fatal (reading_filename, *reading_lineno_ptr,
  1008.                 "the `word' function takes a one-origin \
  1009. index argument");
  1010.       else
  1011.         fatal ("the `word' function takes a one-origin index argument");
  1012.     }
  1013.  
  1014.       p2 = p3;
  1015.       while ((p = find_next_token (&p2, &len)) != 0)
  1016.     if (--i == 0)
  1017.       break;
  1018.       if (i == 0)
  1019.     o = variable_buffer_output (o, p, len);
  1020.  
  1021.       free (text);
  1022.       free (p3);
  1023.       break;
  1024.  
  1025.     case function_words:
  1026.       /* Expand the argument.  */
  1027.       text = expand_argument (text, end);
  1028.  
  1029.       i = 0;
  1030.       p2 = text;
  1031.       while (find_next_token (&p2, (unsigned int *) 0) != 0)
  1032.     ++i;
  1033.  
  1034.       {
  1035.     char buf[20];
  1036.     sprintf (buf, "%d", i);
  1037.     o = variable_buffer_output (o, buf, strlen (buf));
  1038.       }
  1039.  
  1040.       free (text);
  1041.       break;
  1042.  
  1043.     case function_findstring:
  1044.       /* Get two comma-separated arguments and expand each one.  */
  1045.       count = 0;
  1046.       for (p = text; p < end; ++p)
  1047.     {
  1048.       if (*p == startparen)
  1049.         ++count;
  1050.       else if (*p == endparen)
  1051.         --count;
  1052.       else if (*p == ',' && count <= 0)
  1053.         break;
  1054.     }
  1055.       if (p == end)
  1056.     BADARGS ("findstring");
  1057.       text = expand_argument (text, p);
  1058.  
  1059.       p = expand_argument (p + 1, end);
  1060.  
  1061.       /* Find the first occurrence of the first string in the second.  */
  1062.       i = strlen (text);
  1063.       if (sindex (p, 0, text, i) != 0)
  1064.     o = variable_buffer_output (o, text, i);
  1065.       
  1066.       free (p);
  1067.       free (text);
  1068.       break;
  1069.       
  1070.     case function_addsuffix:
  1071.     case function_addprefix:
  1072.       /* Get two comma-separated arguments and expand each one.  */
  1073.       count = 0;
  1074.       for (p = text; p < end; ++p)
  1075.     {
  1076.       if (*p == startparen)
  1077.         ++count;
  1078.       else if (*p == endparen)
  1079.         --count;
  1080.       else if (*p == ',' && count <= 0)
  1081.         break;
  1082.     }
  1083.       if (p == end)
  1084.     BADARGS (function == function_addsuffix ? "addsuffix" : "addprefix");
  1085.       text = expand_argument (text, p);
  1086.       i = strlen (text);
  1087.  
  1088.       p2 = expand_argument (p + 1, end);
  1089.       
  1090.       p3 = p2;
  1091.       while ((p = find_next_token (&p3, &len)) != 0)
  1092.     {
  1093.       if (function == function_addprefix)
  1094.         o = variable_buffer_output (o, text, i);
  1095.       o = variable_buffer_output (o, p, len);
  1096.       if (function == function_addsuffix)
  1097.         o = variable_buffer_output (o, text, i);
  1098.       o = variable_buffer_output (o, " ", 1);
  1099.       doneany = 1;
  1100.     }
  1101.       if (doneany)
  1102.     /* Kill last space.  */
  1103.     --o;
  1104.       
  1105.       free (p2);
  1106.       free (text);
  1107.       break;
  1108.       
  1109.     case function_dir:
  1110.     case function_basename:
  1111.       /* Expand the argument.  */
  1112.       text = expand_argument (text, end);
  1113.  
  1114.       p3 = text;
  1115.       while ((p2 = find_next_token (&p3, &len)) != 0)
  1116.     {
  1117.       p = p2 + len;
  1118.       while (p >= p2 && *p != (function == function_dir ? '/' : '.'))
  1119.         --p;
  1120.       if (p >= p2)
  1121.         {
  1122.           if (function == function_dir)
  1123.         ++p;
  1124.           o = variable_buffer_output (o, p2, p - p2);
  1125.         }
  1126.       else if (function == function_dir)
  1127.             o = variable_buffer_output (o, "./", 2);
  1128.       else
  1129.         /* The entire name is the basename.  */
  1130.         o = variable_buffer_output (o, p2, len);
  1131.  
  1132.       o = variable_buffer_output (o, " ", 1);
  1133.       doneany = 1;
  1134.     }
  1135.       if (doneany)
  1136.     /* Kill last space.  */
  1137.     --o;
  1138.       
  1139.       free (text);
  1140.       break;
  1141.       
  1142.     case function_notdir:
  1143.     case function_suffix:
  1144.       /* Expand the argument.  */
  1145.       text = expand_argument (text, end);
  1146.  
  1147.       p3 = text;
  1148.       while ((p2 = find_next_token (&p3, &len)) != 0)
  1149.     {
  1150.       p = p2 + len;
  1151.       while (p >= p2 && *p != (function == function_notdir ? '/' : '.'))
  1152.         --p;
  1153.       if (p >= p2)
  1154.         {
  1155.           if (function == function_notdir)
  1156.         ++p;
  1157.           o = variable_buffer_output (o, p, len - (p - p2));
  1158.         }
  1159.       else if (function == function_notdir)
  1160.         o = variable_buffer_output (o, p2, len);
  1161.  
  1162.       if (function == function_notdir || p >= p2)
  1163.         {
  1164.           o = variable_buffer_output (o, " ", 1);
  1165.           doneany = 1;
  1166.         }
  1167.     }
  1168.       if (doneany)
  1169.     /* Kill last space.  */
  1170.     --o;
  1171.  
  1172.       free (text);
  1173.       break;
  1174.     }
  1175.  
  1176.   return o;
  1177. }
  1178.  
  1179. /* Check for a function invocation in *STRINGP.  *STRINGP points at the
  1180.    opening ( or { and is not null-terminated.  If a function invocation
  1181.    is found, expand it into the buffer at *OP, updating *OP, incrementing
  1182.    *STRINGP past the reference and returning nonzero.  If not, return zero.  */
  1183.  
  1184. int
  1185. handle_function (op, stringp)
  1186.      char **op;
  1187.      char **stringp;
  1188.  
  1189. {
  1190.   register unsigned int code;
  1191.   unsigned int maxlen;
  1192.   char *beg = *stringp + 1;
  1193.   char *endref;
  1194.  
  1195.   endref = lindex (beg, beg + MAXFUNCTIONLEN, '\0');
  1196.   maxlen = endref != 0 ? endref - beg : MAXFUNCTIONLEN;
  1197.  
  1198.   for (code = 0; function_table[code].name != 0; ++code)
  1199.     {
  1200.       if (maxlen < function_table[code].len)
  1201.     continue;
  1202.       endref = beg + function_table[code].len;
  1203.       if (isblank (*endref)
  1204.       && !strncmp (function_table[code].name, beg,
  1205.                function_table[code].len))
  1206.     break;
  1207.     }
  1208.   if (function_table[code].name != 0)
  1209.     {
  1210.       /* We have found a call to an expansion-time function.
  1211.      Find the end of the arguments, and do the function.  */
  1212.  
  1213.       char openparen = beg[-1], closeparen = openparen == '(' ? ')' : '}';
  1214.       int count = 0;
  1215.       char *argbeg;
  1216.       register char *p;
  1217.  
  1218.       /* Space after function name isn't part of the args.  */
  1219.       p = next_token (endref);
  1220.       argbeg = p;
  1221.  
  1222.       /* Count nested use of whichever kind of parens we use,
  1223.      so that nested calls and variable refs work.  */
  1224.  
  1225.       for (; *p != '\0'; ++p)
  1226.     {
  1227.       if (*p == openparen)
  1228.         ++count;
  1229.       else if (*p == closeparen && --count < 0)
  1230.         break;
  1231.     }
  1232.  
  1233.       if (count >= 0)
  1234.     {
  1235.       static const char errmsg[]
  1236.         = "unterminated call to function `%s': missing `%c'";
  1237.       if (reading_filename == 0)
  1238.         fatal (errmsg, function_table[code].name, closeparen);
  1239.       else
  1240.         makefile_fatal (reading_filename, *reading_lineno_ptr, errmsg,
  1241.                 function_table[code].name, closeparen);
  1242.     }
  1243.  
  1244.       /* We found the end; expand the function call.  */
  1245.  
  1246.       *op = expand_function (*op, function_table[code].function, argbeg, p);
  1247.       *stringp = p;
  1248.       return 1;
  1249.     }
  1250.  
  1251.   return 0;
  1252. }
  1253.  
  1254. /* Glob-expand LINE.  The returned pointer is
  1255.    only good until the next call to string_glob.  */
  1256.  
  1257. static char *
  1258. string_glob (line)
  1259.      char *line;
  1260. {
  1261.   static char *result = 0;
  1262.   static unsigned int length;
  1263.   register struct nameseq *chain;
  1264.   register unsigned int idx;
  1265.  
  1266.   chain = multi_glob (parse_file_seq
  1267.               (&line, '\0', sizeof (struct nameseq),
  1268.                /* We do not want parse_file_seq to strip `./'s.
  1269.               That would break examples like:
  1270.               $(patsubst ./%.c,obj/%.o,$(wildcard ./*.c)).  */
  1271.                0),
  1272.               sizeof (struct nameseq));
  1273.  
  1274.   if (result == 0)
  1275.     {
  1276.       length = 100;
  1277.       result = (char *) xmalloc (100);
  1278.     }
  1279.  
  1280.   idx = 0;
  1281.   while (chain != 0)
  1282.     {
  1283.       register char *name = chain->name;
  1284.       unsigned int len = strlen (name);
  1285.  
  1286.       struct nameseq *next = chain->next;
  1287.       free ((char *) chain);
  1288.       chain = next;
  1289.  
  1290.       /* multi_glob will pass names without globbing metacharacters
  1291.      through as is, but we want only files that actually exist.  */
  1292.       if (file_exists_p (name))
  1293.     {
  1294.       if (idx + len + 1 > length)
  1295.         {
  1296.           length += (len + 1) * 2;
  1297.           result = (char *) xrealloc (result, length);
  1298.         }
  1299.       bcopy (name, &result[idx], len);
  1300.       idx += len;
  1301.       result[idx++] = ' ';
  1302.     }
  1303.  
  1304.       free (name);
  1305.     }
  1306.  
  1307.   /* Kill the last space and terminate the string.  */
  1308.   if (idx == 0)
  1309.     result[0] = '\0';
  1310.   else
  1311.     result[idx - 1] = '\0';
  1312.  
  1313.   return result;
  1314. }
  1315.